package self.cloud.domain.aliyun;

import com.aliyuncs.exceptions.ClientException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import self.cloud.domain.aliyun.entity.AliyunDomainRecord;
import self.cloud.domain.aliyun.handler.AliyunDomainHandler;
import self.cloud.domain.aliyun.handler.AliyunDomainRecordHandler;
import self.cloud.domain.core.entity.Domain;
import self.cloud.domain.core.entity.DomainRecord;
import self.cloud.domain.network.NetworkBusiness;

@Component
public class AliyunDomainService {
    private static final Logger logger = LoggerFactory.getLogger(AliyunDomainService.class);

    @Autowired
    AliyunDomainHandler aliyunDomainHandler;

    @Autowired
    AliyunDomainRecordHandler aliyunDomainRecordHandler;

    @Autowired
    NetworkBusiness networkBusiness;

    public void set(String domainName, DomainRecord record) {
        logger.debug("[domainName]:{} [record]:{}", domainName, record);

        Domain domain = this.aliyunDomainHandler.findByName(domainName);

        if(domain == null) {
            logger.error("Cannot find Domain [name]:{}", domainName);
            return;
        }

        logger.debug("try find record");

        AliyunDomainRecord saveRecord = this.aliyunDomainRecordHandler.findByRR(domain, record.getRR());

        if(saveRecord == null) {
            logger.debug("Cannot find record");
            saveRecord = new AliyunDomainRecord();
        }else {
            logger.debug("Find record [id]:{}", saveRecord.getId());
        }

        saveRecord.setRR(record.getRR());
        saveRecord.setType(record.getType());
        saveRecord.setValue(record.getValue());

        try {
            this.aliyunDomainRecordHandler.save(saveRecord);
        } catch (ClientException e) {
            logger.warn(e.getErrMsg());
        }
    }
}
